//
//  SleepProvider.swift
//  MoyoungHome
//
//  Created by 李然 on 2022/9/26.
//

import Foundation
import HandyJSON
import RxSwift
import RxCocoa
import SwiftDate

import MYModule


public class SleepProvider:NSObject {
    
    public let constSleepStart = 20
    
    public private(set) var date: Date
    
    
   public init(date:Date) {
        self.date = date
        super.init()
    }
    
    private var day: String {
        return date.day.leadingZero
    }
    
    private var month: String {
        return date.month.leadingZero
    }
    
    private var year: String {
        return date.year.leadingZero
    }
    
    /// 当天数据
    public var curDayDetail: SleepModel {
      
        guard let last = SleepModel.day(date: date) else {
            let sleepModel = SleepModel()
            sleepModel.date = date
            return sleepModel
        }
        
        return last
        
    }
    
    /// 最近7天数据
    public var sevenDaysRecord: [SleepModel] {
        
        let list = SleepModel.sevenday(date: date)
        return list
    }
    
    /// 本周数据
    public var weekRecord: [SleepModel] {
        
        var list = SleepModel.weekDay(date: date)
        
        if list.count < 7 {
            
          let emptyData = (list.count ..< 7).map { _ in
              SleepModel()
            }
            
            list.append(contentsOf: emptyData)
            
        }
        
        return list
    }
    
    /// 当月数据
    public var monthRecord: [SleepModel] {
        let list = SleepModel.month(date: date)
       return list
    }
    
    /// 计算值
    public var calculator: SleepQualityCalculator {
        return SleepQualityCalculator(last7Days: sevenDaysRecord)
    }
    
    /// 当天睡眠心率数据
    public var heartData: [SleepChartDetail] {
       
        let list = HeartRateModel.getHeart24ForSleep(date: date).map {model ->SleepChartDetail in
            
            let formmater = DateFormatter.localDateFormatter(dateFormat: "yyyy-MM-dd")
            
            let date = formmater.string(from: model.date)
            
            return SleepChartDetail(date: date, detail: model.hearts)
        }
       
        return list
    }
    
    /// 当天睡眠HRV数据
    public var hrvData: [SleepChartDetail] {
       
        let list = HRVModel.getHRV24ForSleep(date: date).map {model ->SleepChartDetail in
            
            let formmater = DateFormatter.localDateFormatter(dateFormat: "yyyy-MM-dd")
            
            let date = formmater.string(from: model.date)
            
            return SleepChartDetail(date: date, detail: model.hrvs)
        }
        
        return list
    }
    
    /// 获取7天睡眠体温
    public var sevenDaysTemperature: [TemperatureModel] {
        

        let list = TemperatureModel.sevenday(date: date).map { sqlModel ->TemperatureModel in
            let model = TemperatureModel.getTemperature24ForSleep(date: sqlModel.date)
            return model
        }
        return list
        
    }
    
    /// 所有天体温
    public var allDaysTemperature: [TemperatureModel] {
        
        let list = TemperatureModel.all().map { sqlModel ->TemperatureModel in
            let model = TemperatureModel.getTemperature24ForSleep(date: sqlModel.date)
            return model
        }
        return list
    }
    
    
    
    /// 7天温差
    /// 返回元祖（max: min）
    ///  == 0 显示 (max: 0.1, min: -0.1)
    /// 实际是 >0 存  (max: xxx, min: 0)
    /// < 0 存 (max: 0 , min: xxx)
    public var sevenDaysTemperatureDiff: SleepTemperatureModel {
        
        let models = sevenDaysTemperature
        
        // 每天体温平均数
       let avgs = models.map { $0.avg }
        
        // 总平均值
        var allAvg: [Double] = []
        
        let all = allDaysTemperature
        if !all.isEmpty {
            allAvg = all.map({ $0.avg })
        }
        // 去掉 0
        let totalArr = allAvg.filter { $0 > 0 }
        var total: Double = 0
        if !totalArr.isEmpty {
            total = totalArr.reduce(0, { $0 + $1 })/Double(totalArr.count)
        }
        
        /// 默认最大最小值
        var chartMax = 0.0
        var chartMin = 0.0
        let isSetChartMaxMinAble: Bool = true
        
        let temperatureBarModels = avgs.enumerated().map { (i, avg) ->SleepTemperatureModel.BarModel in
            
            var diff: Double = 0
            
            if avg != 0 {
                // 温差 = 一天平均值 - 总平均值
                diff =  (avg - total)
                print("tettetetet")
                print(diff)
                
            }
            
            var low: Double = -0
            var high: Double = 0
            var isFirstDay: Bool = false
            
            // 第一天需要 +- 0并显示
            if i == 0 && all.count == 1 {
                isFirstDay = true
                diff = 0
                high = 0.1
                low = -0.1
            } else {
                // 保留一位小数
                let str = String(format:"%.1f", diff)
                let sortDiff = Double(str) ?? diff
            
                if sortDiff > 0 {
                    high = sortDiff
                    
                    chartMax = max(chartMax, high)
                    
                } else if sortDiff < 0 {
                    low = sortDiff
                    
                    chartMin = max(chartMin, low)
                }
                
            }
            
            let barModel = SleepTemperatureModel.BarModel(firstDay: isFirstDay, temperatureDiff: diff, chartTuples: (low, high))
        
            return barModel
        }
        
//        chartMax += 0.1
//        chartMin -= 0.1
        
        var dataNumber: SleepTemperatureModel.SleepTemperatureDataNumber = .zero
        if totalArr.count == 1 {
            dataNumber = .one
        } else if totalArr.count > 1 {
            dataNumber = .more
        }
        
        var todayDiffText = "--"
        
        switch dataNumber {
            
        case .zero:
            
            chartMax = 0.3
            chartMin = -0.1
            
            break
            
        case .one:
            todayDiffText = "±0.0"
            chartMax = 0.3
            chartMin = -0.1
            
        case .more:
            
                // 最大值 - 最小值 = 0.4 的倍数
                if chartMax > -chartMin {
                    // 正方向y轴多一点
                    let yu = (chartMax - chartMin).truncatingRemainder(dividingBy: 0.4)
                    chartMax = chartMax - yu + 0.3
                    chartMin = chartMin - 0.1
                } else {
                    
                    // 负方向y轴多一点
                    let yu = (-chartMin - chartMax).truncatingRemainder(dividingBy: 0.4)
                    chartMin = chartMin + yu - 0.3
                    chartMax = chartMax + 0.1
                }

            var todayDiff: Double = 0
            if let last = temperatureBarModels.last {
                todayDiff = last.temperatureDiff
            }
            var symbol = ""
            if todayDiff > 0 {
                symbol = "+"
            }

            var text = "\(String(format: "%@%.1f", symbol, todayDiff))"
            if text == "-0.0" || text == "+0.0" {
                text = "0.0"
            }
            
            todayDiffText = text
            break
            
        }
        
        return SleepTemperatureModel(dataNumber: dataNumber, barModels: temperatureBarModels, isSetChartMaxMinAble: isSetChartMaxMinAble, chartMax: chartMax, chartMin: chartMin, todayTemperatureDiffText: todayDiffText)
        
    }
    
    //和同类用户睡得早
    public func getEarlySleepCompareResult() -> (index:Int,percentage:Int) {
        
        let sleep_time_area_percent = [5, 9, 13, 26, 21, 15, 10]
        let max_percent = 100
        let start_sleep_time = 21
        
     
            let detailArr = curDayDetail.detail
            
        guard detailArr.count > 0 else {
            return (index: 0,percentage: 0 )
        }
        
        let first = detailArr.first!
        
        let startString = first.start
        
      
        let starts = startString.components(separatedBy: ":")
        guard var startHour = Int(starts[0]),
              let startMinute = Int(starts[1]) else {
            
            return (0, 0)
        }
        if (startHour < 12){
            startHour = startHour + 24
        }
        
       
        var index = startHour - start_sleep_time
        
        let addOneMinute = startMinute == 0 ? 0: 1
        index = index + addOneMinute
        
        if (index < 0){
            index = 0
        }
        
        let length = sleep_time_area_percent.count
        if (index >= length){
            index = length - 1
        }
        
        //计算百分比
        var precent = 0
        
        for i in 0...index {
            precent += sleep_time_area_percent[i]
        }
        
        let sPrecent = max_percent - precent
        
        return (index:index, percentage: sPrecent)
        
    }
    
    //和同类用户起得早
    public func getEarlyAwakeCompareResult() ->(index:Int,percentage:Int) {
        
        let wake_time_area_percent = [5, 8, 24, 28, 15, 11, 8]
        let max_percent = 100
        let start_wake_up_time = 5
        let min_total_sleep_time = 240
        
        
        let detailArr = curDayDetail.detail
        let total = curDayDetail.total
        
        guard detailArr.count > 0 else {
            return (index: 0,percentage: 0 )
        }
        
        let last = detailArr.last!
        
        var endString = last.end
        
        let ends = endString.components(separatedBy: ":")
       guard let endHour = Int(ends[0]),
             let endMinute = Int(ends[1]) else {
           return (0, 0)
       }
        
        var index = endHour - start_wake_up_time
        
        let addOneMinute = endMinute == 0 ? 0: 1
        index = index + addOneMinute
        
        if (total < min_total_sleep_time) {
            index = 0
        }
        
        if (index <= 0){
            index = 0
        }
        
        let length = wake_time_area_percent.count
        if (index >= length){
            index = length - 1
        }
        
        //计算百分比
        var precent = 0
        
        for i in 0...index {
            precent += wake_time_area_percent[i]
        }
        
        let sPrecent = max_percent - precent
        
        return (index:index, percentage: sPrecent)
        
    }
    
    //和同类用户睡得少
    public func getLesssleepCompareResult() -> (index:Int,percentage:Int) {
        
        let sleep_time_area_percent = [9, 14, 26, 23, 14, 8, 5]
        let max_percent = 100
        let min_sleep_time = 5
        
        let curDayDetail = curDayDetail
        if curDayDetail.isEmpty {
            return (0, 0)
        }
        let total = curDayDetail.total
        
        var index = total / 60
        
        index = index - min_sleep_time
        
        let addOneMinute = (total%60 == 0 && index > 0 ) ? 0: 1
        index = index + addOneMinute
        
        if (index < 0) {
            index = 0
        }
        let length = sleep_time_area_percent.count;
        if (index >= length){
            index = length - 1
        }
        //计算百分比
        var precent = 0
        
        for i in 0...index {
            precent += sleep_time_area_percent[i]
        }
        
        let sPrecent = max_percent - precent
        
        return (index:index, percentage: sPrecent)
        
    }
    
    public func configModel(_ sleepRecord: SleepModel, list:[SleepChartDetail]) -> HeartRateChartLineConfig? {
        
        guard let fallAsleep = sleepRecord.fallAsleepDate,
              let awake = sleepRecord.awakeDate else {
            
            let startTime = "sleep_fail_asleep".language(with: ["--"])
            let endTime =  "sleep_wake_up".language(with: ["--"])
            let config = HeartRateChartLineConfig(list: [], startTime: startTime, endTime: endTime)
            
            return config
            
        }
        
        /// 计算最大值，最小值，平均值
        var maxValue: Int = 0
        var minValue: Int = 255
        var avg: Int = 0
        
        var totalValues: [Int] = []
        var all: [Int] = []
        
        list.enumerated().forEach {i, model in
            
            all.append(contentsOf: model.detail)
            
            let noZeroDetail = model.detail.filter ({ data in  data > 0 })
            totalValues.append(contentsOf: noZeroDetail)
            
        }
        
        totalValues.forEach {
            
            maxValue = max(maxValue, $0)
            minValue = min(minValue, $0)
            
        }
        
        if minValue > maxValue {
            minValue = maxValue
        }
        
        if !totalValues.isEmpty {
            let allValue = totalValues.reduce(0, { $0 + $1 })
            avg = allValue/totalValues.count
        }
        
        var startTime = fallAsleep.toString(.custom("MM/dd HH:mm"))
        var endTime = awake.toString(.custom("MM/dd HH:mm"))
        
        startTime = "sleep_fail_asleep".language(with: [startTime])
        endTime =  "sleep_wake_up".language(with: [endTime])
        let config = HeartRateChartLineConfig(avg: avg, high: maxValue, low: minValue, list: all, startTime: startTime, endTime: endTime)
    
        return config

    }
    
}

public extension SleepProvider {
    
    enum DateType {
        case fallAsleep
        case wakeUp
    }
    
}


